<?php
namespace app\admin\module;

use app\common\model\Permission;
use app\common\model\RolePermission;

class PermissionModule {

    /**
     * 所有的级数
     */
    public static function tree(){
        $count = Permission::where([])->count();
        $all = Permission::where([])->limit(0,$count)->order('sort','desc')->select()->toArray();
        return self::makeTree(0,$all);
    }

    public static function makeTree($pid,&$data){
        $res = [];
        foreach($data as $key =>$val){
            if($val['pid'] == $pid){
                array_push($res,$val);
                unset($data[$key]);
            }
        }
        foreach($res as $key => $val){
            $res[$key]['sub'] = self::makeTree($val['id'],$data);
        }
        return $res;
    }


    public static function getMenu($role){
         return RolePermission::alias('rp')
            ->join('permission p','rp.permission_id = p.id')
            ->where(['rp.role_id'=>$role])
             ->where([['p.type','in',[0,1]]])
             ->field('p.*')
             ->order("p.sort",'desc')
             ->select()->toArray();
    }

    public static function getAllMenu(){
        return Permission::where([['type','in',[0,1]]])->order('sort','desc')->select()->toArray();
    }

    public static function getPermission($role){
        $permission = RolePermission::alias('rp')
            ->join('permission p','rp.permission_id = p.id')
            ->where(['rp.role_id'=>$role])
            ->where(['p.type'=>2])
            ->field('p.*')
            ->select()->toArray();
        $final = [];
        foreach($permission as $key => $val){
            array_push($final,strtolower($val['controller'].":".$val['action']));
        }
        return $final;
    }

    public static function getAllPermission(){
        $permission =  Permission::where(['type'=>2])->select()->toArray();
        $final = [];
        foreach($permission as $key => $val){
            array_push($final,strtolower($val['controller'].":".$val['action']));
        }
        return $final;
    }
}